<template>
    <a-layout class="layout">
        <a-layout-content class="content">
            <div class="tip" ref="tip">以下由AI汇总生成，请您注意核实或修改</div>
            <div
                class="result"
                ref="scrollContainer"
                :style="{ height: contentHeight + 'px' }"
                contenteditable="true"
            >
                <div v-for="(item, index) in results" :key="index">
                    <div v-if="item.type == 'title'" class="title">
                        <img src="@/assets/img/diagnose/report_icon_1.png" />{{ item.word }}
                    </div>
                    <div v-else class="article">
                        {{ item.word
                        }}<span v-if="show_loading && index + 1 == results_len" class="loading_dot"
                            >&bull;</span
                        >
                    </div>
                </div>
            </div>
            <div class="btns" ref="btns">
                <div class="publish_todo" v-if="button_status == 0">
                    <a-button
                        style="height: 50px; width: 100%"
                        type="primary"
                        block
                        html-type="submit"
                        @click="sendReportClick"
                    >
                        发送至患者
                    </a-button>
                </div>
                <div class="publish_todo" v-if="button_status == 1">
                    <a-button
                        style="height: 50px; width: 46%"
                        type="primary"
                        block
                        html-type="submit"
                        disabled
                    >
                        发送至患者
                    </a-button>
                    <a-button
                        style="height: 50px; width: 46%"
                        type="primary"
                        block
                        html-type="submit"
                        @click="stopTreatmentClick"
                    >
                        结束诊疗
                    </a-button>
                </div>
                <div class="publish_done" v-if="button_status == 2">
                    <div class="ok_tip">已经发送至患者</div>
                    <a-button
                        style="height: 50px; width: 100%"
                        type="primary"
                        block
                        html-type="submit"
                        @click="stopTreatmentClick"
                    >
                        结束诊疗
                    </a-button>
                </div>
            </div>
        </a-layout-content>
    </a-layout>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue';
import { VoiceToTextPost } from '@/apis/user.ts';
import { errorHandler } from '@/utils';

// import { DisgnosisReportGet } from '@/apis/doctor-server.ts'
const contentHeight = ref(0);
const tip = ref(null);
const btns = ref(null);
const scrollContainer = ref(null);
const results = ref([]);
const results_len = ref(0);
const show_loading = ref(false);
const button_status = ref(0);
let queues = [];

let ws = null;
let ws_open = false;

const sendReportClick = () => {
    button_status.value = 1;
};
//结束治疗
const stopTreatmentClick = () => {
    button_status.value = 2;
};

async function importCommonConfig() {
    const res = await import('../../../config/index.js');
    return res;
}

//录音转文字
const setVoiceToText = async callback => {
    try {
        const {
            code,
            message: msg,
            data,
        } = await VoiceToTextPost({
            requestBody: {
                cos_url:
                    'https://clinic-voice-1319532402.cos.ap-beijing.myqcloud.com/65bb6e56a626c722709a7157-%E9%97%AE%E8%AF%8A%E6%B5%8B%E8%AF%95%E8%AF%AD%E9%9F%B3.m4a',
                medical_record_id: '660d3ee857da8d1e03669a03',
                media_record_id: '660d3ee857da8d1e03669a02',
            },
        });
        if (code === 200) {
            console.log(`录音转文字`, data);
            if (typeof callback == 'function') {
                callback();
            }
        } else {
            message.error(msg);
        }
    } catch (error) {
        errorHandler(error);
    }
};

//socket
async function connectSocket() {
    const curEnv = process.env.APP_DEPLOY_ENV;
    const curConfig = await importCommonConfig();
    let baseURL = curConfig[curEnv].apiHost;
    console.log(baseURL);
    let wsHost = baseURL;
    if (baseURL.indexOf('https://') > -1) {
        wsHost = baseURL.replace('https://', 'wss://');
    } else if (baseURL.indexOf('http://') > -1) {
        wsHost = baseURL.replace('http://', 'ws://');
    }
    console.log(wsHost);
    // const wsURL = `${baseURL}/pisces/ws/clinic/analysis_medical/case_history`
    const wsURL = `${wsHost}/pisces/ws/clinic/analysis_medical/AI_detail`;

    // const headers = {
    //     Cookie: 'login_token=LaGvACWEFe7kJuvHqKDDpbRMwNbtYg5Jgw8UhIoq_8s; Path=/; HttpOnly; Expires=Sat, 06 Apr 2024 09:57:25 GMT;',
    // };
    /*
   ws获取AI内容：
   url：xxhuisheng.com/pisces/ws/clinic/analysis_medical/AI_detail
   message： {"medical_record_id": "660d3ee857da8d1e03669a03"}
   */
    queues = [];
    ws = new WebSocket(wsURL);
    ws_open = true;
    ws.onopen = function () {
        console.log('Connection open ...');
        // ws.send("Hello WebSockets!");
        ws.send(JSON.stringify({ medical_record_id: '660a6f514ed414f9241ed6f6' }));
    };

    ws.onmessage = function (evt) {
        console.log('Received Message: ' + evt.data);
        // ws.close();
        try {
            let json = JSON.parse(evt.data);
            queues.push(json);
        } catch (err) {
            console.log(err);
        }
    };

    ws.onclose = function () {
        console.log('Connection closed.');
        ws_open = false;
    };
}

// 生命周期钩子
onMounted(async () => {
    console.log(`The initial count is .`);

    window.addEventListener('flutterInAppWebViewPlatformReady', function () {
        window.flutter_inappwebview.callHandler('setTitle', '诊后总结').then(function (result) {
            console.log(result);
        });

        // window.flutter_inappwebview.callHandler('hideTitle', '').then(function(result) {
        //     console.log(result);
        // });
    });
    await nextTick();
    var windowHeight = window.innerHeight;
    console.log(windowHeight, tip.value.clientHeight, btns.value.clientHeight); // 输出窗口
    contentHeight.value = windowHeight - tip.value.clientHeight - btns.value.clientHeight;

    consumers();

    let debug = false;
    if (debug) {
        producter();
    } else {
        setVoiceToText(() => {
            connectSocket();
        });
    }
});

function testDatas() {
    return [
        /*
        { "姓名": "李征\n" },
        { "电话": "1234567\n" },
        { "年龄": "\n" },
        { "主诉": "三周前做了锥切手术，伤口还没有完全痊愈。\n" },
        { "现病史": "患者因HPV16感染，CIN2级，进行了锥形切除手术。术后三周，伤口处有疼痛和少量出血。\n" },
        { "既往史": "\n" },
        { "体格检查": "\n" },
        { "辅助检查": "建议复查，安排妇科检查。\n" },
        { "初步诊断": "锥形切除术后伤口恢复情况。\n" },
        { "治疗方案": "建议患者下周复查，注意不要进行剧烈运动，直到伤口完全愈合。如果疼痛、出血持续或有发烧，应立即联系医生。\n" },
        { "本次就诊总结": "\n患者李征，因HPV16感染，CIN2级，三周前接受了锥形切除手术。目前伤口未完全愈合，有疼痛和少量出血，但无发烧或异常分泌物。建议下周复查，并注意伤口护理，避免剧烈运动，如有疼痛、出血加重或发烧，应立即联系医生。" }
        */
        {
            诊中小结:
                '\n患者：李征，三周前因HPV16感染（等级CIN2）接受锥形切除手术。目前主诉伤口疼痛，偶尔有少量出血，担心恢复不良。患者未出现发烧症状，但有少量正常颜色的分泌物。\n\n',
        },
        {
            诊后注意:
                '\n1. 注意伤口的日常护理，避免感染。\n2. 避免剧烈运动，以免影响伤口愈合。\n3. 观察伤口是否有异常症状如加重的疼痛、异常分泌物或发烧，如有应立即联系医生。\n4. 下周复查，以评估伤口愈合情况。\n5. 伤口一般需要四到六周恢复，但具体时间根据个人情况而定。\n\n',
        },
        {
            就诊总结:
                '\n患者李征，因HPV16感染，CIN2级，三周前接受锥形切除手术。目前伤口疼痛，偶尔出血，无发烧，有少量正常颜色分泌物。医生建议下周复查，并进行妇科检查以评估伤口愈合情况。患者需注意伤口护理，避免剧烈运动，观察伤口状况，并在有异常时及时联系医生。',
        },
    ];
}

// 滚动到底部的函数
function scrollToBottom() {
    if (scrollContainer.value) {
        scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    }
}

//模拟动态push
async function producter() {
    let words = testDatas();
    ws_open = true;
    queues.value = [];
    for (let item of words) {
        queues.push(item);
        await sleep(10000);
    }
    ws_open = false;
}

//消费者动态渲染数据
async function consumers() {
    let index = 0;
    while (true) {
        if (index >= queues.length || queues.length == 0) {
            if (ws_open == true) {
                show_loading.value = true;
            } else {
                show_loading.value = false;
            }
            await sleep(1000);

            continue;
        }
        show_loading.value = false;
        let item = queues[index];
        console.log(item);
        for (let key in item) {
            await updateText(key, 'title');
            let segments = item[key].split('\n');
            let blanks = 0;
            for (let segment of segments) {
                if (segment == '') {
                    blanks++;
                    continue;
                }
                await updateText(segment, 'article');
            }
            if (segments.length == blanks) {
                await updateText('暂无', 'article');
            }

            await sleep(300);
        }
        index++;
    }
}

async function updateText(word, type) {
    results.value.push({ type: type, word: '' });
    let len = results.value.length;
    results_len.value = len;
    let str = '';
    let index = 0;
    for (let i = 0; i < word.length; i++) {
        str += word[index++];
        results.value[len - 1].word = str;
        await sleep(40);
        scrollToBottom();
    }
}

function sleep(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    });
}
</script>

<style scoped>
.content {
    background-color: #fff;
}

.tip {
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 14px;
    color: #777;
}

.result {
    /* flex: 1; */
    border: 1px solid #0078c3;
    border-radius: 10px;
    margin: 0px 14px 0px 14px;
    padding: 14px;
    box-sizing: border-box;
    color: #333;
    overflow-y: auto;
}

.title {
    font-weight: bold;
    font-size: 16px;
    color: #555;
    line-height: 50px;
}

.title img {
    width: 16px;
    height: 16px;
    margin-right: 10px;
}

.article {
    font-size: 15px;
    color: #555;
    line-height: 20px;
}

.btns {
    border-top: 1px solid #ddd;
    height: 90px;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
}

.publish_todo {
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.publish_done {
    width: 100%;
    text-align: center;
}
.publish_done .ok_tip {
    color: #777;
    font-size: 12px;
    line-height: 30px;
}

/* 定义闪烁动画 */
@keyframes blink {
    0% {
        color: rgba(24, 144, 255, 1);
    }

    20% {
        color: rgba(24, 144, 255, 0.9);
    }

    40% {
        color: rgba(24, 144, 255, 0.7);
    }

    60% {
        color: rgba(24, 144, 255, 0.4);
    }

    80% {
        color: rgba(24, 144, 255, 0.2);
    }

    100% {
        color: rgba(24, 144, 255, 0.1);
    }
}

.loading_dot {
    color: rgba(24, 144, 255, 1);
    font-size: 30px;
    vertical-align: middle;
    animation: blink 1s infinite;
}
</style>
